var fs = require('fs');
var WorkspaceProxy = require('../../../proxy/workspace.js');
var _ = require('lodash');
var logger = require('log4js').getLogger();

exports.addWkpMember = function (req, res, next) {
    var workspace_id = req.params.workspace_id;
    var newMember = req.body;
    WorkspaceProxy.getWorkspaceById(workspace_id, function (err, workspace) {
        if (err) {
            logger.error(err);
            return res.format_json(null, 500, err);
        }
        var wkpMembers = workspace.user;
        if (_.findIndex(wkpMembers, {shortId: newMember.shortId}) >= 0) {
            return res.format_json({}, 200, "成员已存在");
        }
        wkpMembers.push(newMember);
        WorkspaceProxy.updateMembers(workspace, wkpMembers, function (err, data) {
            if (err) {
                logger.error(err);
                res.status(500);
                return res.format_json(null, 500, err);
            }
            return res.format_json(data, 200, null);
        });
    })
},
exports.removeWkpMember = function (req, res, next) {
    var workspace_id = req.params.workspace_id;
    var shortId = req.query.user;
    WorkspaceProxy.getWorkspaceById(workspace_id, function (err, workspace) {
        if (err) {
            logger.error(err);
            return res.format_json(null, 500, err);
        }
        var deleted = _.remove(workspace.user, function (it) {
            return it.shortId == shortId;
        });
        if (deleted.length == 0) {
            return res.format_json({}, 200, "成员不存在");
        }
        WorkspaceProxy.updateMembers(workspace, workspace.user, function (err, data) {
            if (err) {
                logger.error(err);
                res.status(500);
                return res.format_json(null, 500, err);
            }
            return res.format_json(data, 200, null);
        });
    })
},
exports.editWkpMember = function (req, res, next) {
    var workspace_id = req.params.workspace_id;
    var member = req.body;
    WorkspaceProxy.getWorkspaceById(workspace_id, function (err, workspace) {
        if (err) {
            logger.error(err);
            return res.format_json(null, 500, err);
        }
        var wkpMembers = workspace.user;
        var index = _.findIndex(wkpMembers, {shortId: member.shortId});
        if (index < 0) {
            return res.format_json({}, 200, "成员不已存在");
        }
        wkpMembers[index].role = member.role;
        WorkspaceProxy.updateMembers(workspace, wkpMembers, function (err, data) {
            if (err) {
                logger.error(err);
                res.status(500);
                return res.format_json(null, 500, err);
            }
            return res.format_json(data, 200, null);
        });
    })
};